<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑用户' : '新建用户'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      label-position="left"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="formData.username"
              placeholder="请输入用户名"
              :disabled="isEdit"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="realName">
            <el-input
              v-model="formData.realName"
              placeholder="请输入真实姓名"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="formData.email"
              placeholder="请输入邮箱地址"
              type="email"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号码"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <el-select
              v-model="formData.role"
              placeholder="请选择用户角色"
              style="width: 100%"
            >
              <el-option
                v-for="role in roleOptions"
                :key="role.value"
                :label="role.label"
                :value="role.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="active">启用</el-radio>
              <el-radio label="inactive">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item v-if="!isEdit" label="密码" prop="password">
        <el-input
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          show-password
          clearable
        />
      </el-form-item>
      
      <el-form-item v-if="!isEdit" label="确认密码" prop="confirmPassword">
        <el-input
          v-model="formData.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
          show-password
          clearable
        />
      </el-form-item>
      
      <el-form-item label="部门" prop="department">
        <el-input
          v-model="formData.department"
          placeholder="请输入所属部门"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="职位" prop="position">
        <el-input
          v-model="formData.position"
          placeholder="请输入职位"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  user: {
    type: Object,
    default: null
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'submit'])

// 响应式数据
const formRef = ref()
const loading = ref(false)

const formData = reactive({
  username: '',
  realName: '',
  email: '',
  phone: '',
  role: '',
  status: 'active',
  password: '',
  confirmPassword: '',
  department: '',
  position: '',
  remark: ''
})

const roleOptions = [
  { label: '管理员', value: 'admin' },
  { label: '医生', value: 'doctor' },
  { label: '护士', value: 'nurse' },
  { label: '操作员', value: 'operator' }
]

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单验证规则
const formRules = computed(() => {
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
      { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
    ],
    realName: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' },
      { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    role: [
      { required: true, message: '请选择用户角色', trigger: 'change' }
    ],
    status: [
      { required: true, message: '请选择用户状态', trigger: 'change' }
    ]
  }
  
  // 新建用户时添加密码验证
  if (!props.isEdit) {
    rules.password = [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
      { 
        pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
        message: '密码必须包含大小写字母和数字', 
        trigger: 'blur' 
      }
    ]
    
    rules.confirmPassword = [
      { required: true, message: '请再次输入密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== formData.password) {
            callback(new Error('两次输入的密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }
  
  return rules
})

// 方法
const resetForm = () => {
  Object.assign(formData, {
    username: '',
    realName: '',
    email: '',
    phone: '',
    role: '',
    status: 'active',
    password: '',
    confirmPassword: '',
    department: '',
    position: '',
    remark: ''
  })
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

const fillForm = (user) => {
  if (user) {
    Object.assign(formData, {
      username: user.username || '',
      realName: user.realName || '',
      email: user.email || '',
      phone: user.phone || '',
      role: user.role || '',
      status: user.status || 'active',
      department: user.department || '',
      position: user.position || '',
      remark: user.remark || ''
    })
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const submitData = { ...formData }
    
    // 编辑时移除密码相关字段
    if (props.isEdit) {
      delete submitData.password
      delete submitData.confirmPassword
    }
    
    emit('submit', submitData)
  } catch (error) {
    ElMessage.error('请检查表单输入')
  } finally {
    loading.value = false
  }
}

// 监听器
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      if (props.isEdit && props.user) {
        fillForm(props.user)
      } else {
        resetForm()
      }
    }
  },
  { immediate: true }
)

watch(
  () => props.user,
  (newUser) => {
    if (props.visible && props.isEdit && newUser) {
      fillForm(newUser)
    }
  },
  { deep: true }
)
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 80px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  :deep(.el-dialog__body) {
    padding: 15px 15px 0 15px;
  }
  
  :deep(.el-form) {
    label-width: 70px !important;
  }
  
  :deep(.el-col) {
    width: 100% !important;
    margin-bottom: 10px;
  }
}

@media (max-width: 480px) {
  :deep(.el-dialog) {
    width: 100% !important;
    margin: 0;
    height: 100vh;
    border-radius: 0;
  }
  
  :deep(.el-dialog__header) {
    padding: 15px 20px;
  }
  
  :deep(.el-dialog__body) {
    padding: 10px 20px 0 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;
  }
  
  :deep(.el-dialog__footer) {
    padding: 15px 20px;
  }
}
</style>